import {
  ForbiddenException,
  Injectable,
  NotFoundException
} from '@nestjs/common'
import { PrismaService } from 'src/prisma/prisma.service'
import { HttpService } from '@nestjs/axios'
import { lastValueFrom } from 'rxjs'
import { JwtService } from '@nestjs/jwt'
import { Prisma } from '@prisma/client'

interface IWxResponse {
  openid: string
  session_key: string
}

@Injectable()
export class UserService {
  constructor(
    private readonly prismaService: PrismaService,
    private readonly httpService: HttpService,
    private readonly jwtService: JwtService
  ) {}

  async userLogin(code: string) {
    const resObser = this.httpService.get<IWxResponse>(
      'https://api.weixin.qq.com/sns/jscode2session',
      {
        params: {
          appid: process.env.APP_ID,
          secret: process.env.APP_SECRET,
          js_code: code,
          grant_type: 'authorization_code'
        }
      }
    )
    const wxRes = await (await lastValueFrom(resObser)).data
    const payload = {
      openid: wxRes.openid
    }
    try {
      const user = await this.prismaService.user.create({
        data: {
          openid: wxRes.openid
        }
      })
      return {
        user,
        token: this.jwtService.sign(payload)
      }
    } catch (error) {
      const user = await this.prismaService.user.findUnique({
        where: {
          openid: wxRes.openid
        }
      })
      return {
        user,
        token: this.jwtService.sign(payload)
      }
    }
  }

  async getUserById(id: number) {
    try {
      const user = await this.prismaService.user.findFirst({
        where: {
          id
        }
      })
      return user
    } catch (error) {
      throw new NotFoundException('未找到该用户')
    }
  }

  async updateUser(token: string, data: Prisma.UserUpdateInput) {
    try {
      const vUser = await this.jwtService.verify(token)
      const user = await this.prismaService.user.update({
        where: {
          openid: vUser.openid
        },
        data
      })
      return user
    } catch (error) {
      throw new ForbiddenException('没有权限')
    }
  }
}
